import axios from "axios";
import qs from "qs";
import router from "@/router/index";
import message from './message';

//正式
axios.defaults.baseURL = import.meta.env.VITE_BASEURL

//post请求头
axios.defaults.headers.post["Content-Type"] ="application/x-www-form-urlencoded;charset=UTF-8";

//设置超时
axios.defaults.timeout = 300000;

axios.interceptors.request.use(
    config => {
        localStorage.getItem('token') && (config.headers.token = localStorage.getItem('token'));
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        //token 失效
        if(response.data.code == 1000){
            message.error('登录超时,请重新登录!');
            let urlArr = location.href.split('/');
            localStorage.clear();
            router.replace({
                path: '/',
                query: {
                    redirect: '/' + urlArr[urlArr.length-1]
                }
            })
            return Promise.resolve(response);
        }

        if (response.status == 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        console.log(`异常请求：${JSON.stringify(error.message)}`);
    }
);

export default {
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url,
                data: qs.stringify(data),
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            });
        })
    },

    get(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                params: data,
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
        })
    }
};

